<template>
    <el-card style="width: 800px">
        <el-dialog
            v-model="countdownVisible"
            title="任务执行进度"
            width="45%"
            :close-on-click-modal="false"
            :show-close="false"
        >
            <div class="task-container">
                <div 
                    v-for="task in activeTasks" 
                    :key="task.id" 
                    class="task-item"
                >
                    <div class="task-header">
                        <span class="task-name">{{ task.name }}</span>
                        <span class="task-time">{{ formatTime(task.remaining) }}</span>
                    </div>
                    <el-progress
                        :percentage="task.percentage"
                        :status="getProgressStatus(task.percentage)"
                        :stroke-width="16"
                    />
                </div>
                
                <div class="total-progress">
                    <el-progress 
                        :percentage="totalProgress"
                        status="success"
                        :stroke-width="20"
                        :format="() => `总进度：${totalProgress}%`"
                    />
                </div>
            </div>
        </el-dialog>

        <template #header>
            <div style="display: flex;align-items: center;justify-content: center;">
                <img src="./112_姜饼小人.svg" alt="" style="height: 40px;width: 40px">
                <span class="styled-text">青岛大学刷课</span>
            </div>
        </template>
        
        <el-form :model="form" label-width="auto">
            <el-form-item label="用户唯一token">
                <el-input 
                    v-model="form.token"  
                    @keydown.enter="getAllClass"
                    placeholder="请输入访问令牌"
                />
            </el-form-item>

            <el-form-item>
                <el-button 
                    style="margin: auto" 
                    type="primary" 
                    @click="getAllClass"
                    :loading="loadingCourses"
                >
                    获取所有课程
                </el-button>
            </el-form-item>
            <el-form-item>
                <el-table 
                    :data="classList" 
                    border 
                    height="245" 
                    style="width: 100%" 
                    @selection-change="handleCourseSelect"
                >
                    <el-table-column 
                        type="selection" 
                        width="55" 
                        :selectable="isCourseSelectable"
                    />
                    <el-table-column prop="name" label="课程名称" width="300">
                        <template #default="{ row }">
                            {{ row.name }}
                            <el-tag
                                v-if="parseProgress(row.progress) >= 100"
                                type="success"
                                effect="light"
                                size="small"
                                class="ml-2"
                            >
                                已完成
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="progress" label="进度" width="180">
                        <template #default="{ row }">
                            <el-tag :type="progressTagType(row.progress)">
                                {{ row.progress }}
                                <el-icon v-if="parseProgress(row.progress) >= 100" class="ml-1">
                                    <Select />
                                </el-icon>
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="teacherName" label="授课教师" />
                </el-table>
            </el-form-item>

            <el-form-item label="选择任务类型">
                <el-radio-group v-model="form.status">
                    <el-radio :value="1" border>刷课</el-radio>
                    <el-radio :value="2" border>做作业</el-radio>
                </el-radio-group>
            </el-form-item>

            <StudyTask 
                v-if="form.status === 1"
                :token="form.token"
                :selected-courses="selectedCourses"
                @update-tasks="updateTasks"
            />
            
            <HomeworkTask 
                v-if="form.status === 2"
                :token="form.token"
                :selected-courses="selectedCourses"
                @update-tasks="updateTasks"
            />
        </el-form>
    </el-card>
</template>

<script setup lang="ts">
import { reactive, ref, computed } from 'vue'
import axios from "axios";
import { ElMessage, ElNotification } from "element-plus";
import { Select } from '@element-plus/icons-vue'
import StudyTask from './components/StudyTask.vue'
// @ts-ignore 暂时忽略类型检查，后续需要为HomeworkTask组件添加类型声明
import HomeworkTask from './components/HomeworkTask.vue'

// 课程信息接口定义
interface Course {
    id: string;            // 课程唯一标识
    name: string;          // 课程名称
    progress: string;      // 课程进度（百分比形式，如"85%"）
    teacherName: string;   // 授课教师姓名
    menus: Array<{ courseOpenId: string }>;  // 课程开放ID列表，用于获取课程详情
}

// 全局表单状态
const form = reactive({
    token: '',    // 用户访问令牌
    status: 1,    // 任务类型：1-刷课模式，2-作业模式
})

// 课程相关状态管理
const classList = ref<Course[]>([])           // 所有课程列表
const selectedCourses = ref<Course[]>([])     // 已选择的课程列表
const loadingCourses = ref(false)            // 课程加载状态
const countdownVisible = ref(false)          // 进度弹窗显示状态
const activeTasks = ref<any[]>([])           // 当前活动的任务列表

// 计算总体进度百分比
const totalProgress = computed(() => {
    if (activeTasks.value.length === 0) return 0
    return Math.round(activeTasks.value.reduce((sum, t) => sum + t.percentage, 0) / activeTasks.value.length)
})

// 工具函数：解析进度字符串为数字
const parseProgress = (progress: string) => {
    return parseInt(progress.replace('%', '')) || 0
}

// 判断课程是否可选择
// 刷课模式：仅未完成课程可选
// 作业模式：所有课程可选
const isCourseSelectable = (row: Course) => {
    return form.status === 1 ? parseProgress(row.progress) < 100 : true
}

// 根据进度值确定标签类型
// 完成(100%): success
// 过半(>=50%): warning
// 未过半(<50%): danger
const progressTagType = (progress: string) => {
    const value = parseProgress(progress)
    return value >= 100 ? 'success' : value >= 50 ? 'warning' : 'danger'
}

// 格式化剩余时间为 MM:SS 格式
const formatTime = (seconds: number) => {
    return `${Math.floor(seconds / 60).toString().padStart(2, '0')}:${Math.floor(seconds % 60).toString().padStart(2, '0')}`
}

// 获取进度条状态
const getProgressStatus = (percentage: number) => {
    return percentage >= 100 ? 'success' : 'primary'
}

// 获取课程列表数据
const getAllClass = async () => {
    if (!form.token) {
        ElMessage.warning('请先输入访问令牌')
        return
    }

    loadingCourses.value = true
    try {
        const response = await axios.post('/jxjyzx/LearningSpace/list', {
            isPass: 0,      // 0表示获取所有课程
            pageNum: 1,     // 页码
            pageSize: 1000  // 每页数量，设置较大值以获取全部数据
        }, {
            headers: { 'access-token': form.token }
        })

        classList.value = response.data.data.list
        ElNotification.success(`获取到 ${classList.value.length} 门课程`)
    } catch (error) {
        ElMessage.error('获取课程失败，请检查令牌有效性')
    } finally {
        loadingCourses.value = false
    }
}

// 处理课程选择变化
const handleCourseSelect = (courses: Course[]) => {
    if (form.status === 1) {
        // 刷课模式：过滤已完成课程
        const valid = courses.filter(c => parseProgress(c.progress) < 100)
        if (courses.length !== valid.length) {
            ElMessage.warning(`已自动排除${courses.length - valid.length}门已完成课程`)
        }
        selectedCourses.value = valid
    } else {
        // 作业模式：保留所有选中课程
        selectedCourses.value = courses
    }
}

// 更新任务状态并控制进度弹窗
const updateTasks = (tasks: any) => {
    activeTasks.value = tasks
    countdownVisible.value = tasks.length > 0
}
</script>

<style scoped>
/* 标题文字样式：渐变色背景和阴影效果 */
.styled-text {
    font-size: 30px;
    font-weight: bold;
    background: linear-gradient(to right, #f6d365, #fda085);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

/* 任务列表容器：最大高度限制和滚动 */
.task-container {
    max-height: 60vh;
    overflow-y: auto;
}

/* 单个任务项样式 */
.task-item {
    margin: 15px 0;
    padding: 12px;
    border-radius: 8px;
    background: #f8f9fa;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

/* 任务头部布局 */
.task-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
    font-size: 14px;
}

/* 任务名称样式：单行省略 */
.task-name {
    color: #333;
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

/* 任务时间样式 */
.task-time {
    color: #666;
    margin-left: 15px;
}

/* 总进度条容器样式 */
.total-progress {
    margin-top: 20px;
    padding-top: 15px;
    border-top: 1px solid #e4e7ed;
}

/* 表格标签样式调整 */
:deep(.el-table__row) .el-tag {
    margin: 2px 0;
    min-width: 80px;
    justify-content: center;
}

/* 进度条动画效果 */
:deep(.el-progress-bar__inner) {
    transition: all 0.3s ease;
}

/* 通用边距类 */
.ml-2 {
    margin-left: 8px;
}
</style>